<template>
  <var-loading description="登录中...." type="circle" :loading="loading">
    <div class="container pt-1.5">
      <div class="content">
        <img class="w-[155px] h-[60px] mb-3" src="../../assets/img/logo.png" />
        <var-form ref="form">
          <var-space direction="column" :size="[14, 0]">
            <var-input
              class="mt-2"
              placeholder="请输入手机号"
              :rules="[(v) => !!v || '手机号不能为空']"
              v-model="formData.phone"
            />
            <var-input
              class="mt-0.5"
              type="password"
              placeholder="请输入密码"
              :rules="[(v) => !!v || '密码不能为空']"
              v-model="formData.password"
            />
          </var-space>
        </var-form>
        <var-button
          class="mt-[35px]"
          style="border-radius: 30px; padding: 22px 0"
          type="success"
          color="#ffc6c9"
          block
          @click="userLogin"
        >
          登录
        </var-button>
      </div>
    </div>
  </var-loading>
</template>

<script setup lang="ts">
import { appLogin } from "../../api/usersApi";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Snackbar } from "@varlet/ui";
interface form {
  phone: string;
  password: string;
}

const router = useRouter();
const formData = reactive<form>({ phone: "admin", password: "123456" });
const form = ref(null);
const loading = ref(false);

const userLogin = async () => {
  const validate = await form.value.validate();
  if (validate) {
    loading.value = true;
    try {
      const { code, data, message } = await appLogin(formData);
      if (code == 200) {
        localStorage.setItem("token", data[0].token);
        localStorage.setItem("phone", data[0].phone);
        setTimeout(() => {
          Snackbar.success({
            content: message,
            duration: 1000,
          });
          loading.value = false;
          router.push({
            path: "/homeIndex",
          });
        }, 1200);
      }
    } catch (e) {
      Snackbar.error(e);
      loading.value = false;
    }
  }
};
onMounted(() => {
  const token = localStorage.getItem("token");
  if (token) {
    router.push({
      path: "/homeIndex",
    });
  }
});
</script>

<style scoped lang="less">
.container {
  height: 100vh;
  background-image: url("@/assets/img/background.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  .content {
    width: 80%;
    height: 60%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
